package IOTWeb.com.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.IOTMain;
import IOTWeb.com.agreementclient.WebServer;
import IOTWeb.com.utils.Utils;
import IOTWeb.com.utils.FileOption;
import IOTWeb.com.utils.H2ConnectionPool;
import IOTWeb.com.utils.LogSet;

/*
 * 上传文件
 * time：2022.2.12
 * @author xu-zhiqiang
 */
public class UploadHandler implements HttpHandler {
	@Override
	public void handle(HttpExchange exchange) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Utils utils = new Utils();
					FileOption fileOption = new FileOption();
					//获取url
					LogSet.logger.info("url:" + exchange.getRequestURI().toString());
					// 获得查询字符串(get)
					String queryString = exchange.getRequestURI().getQuery();
					Map<String, String> queryStringInfo = utils.formData2Dic(queryString);
					String name = queryStringInfo.get("name");
					//获取response头
					Headers responseHeaders = exchange.getResponseHeaders();
					//获取request头
					Headers requestHeaders = exchange.getRequestHeaders();
					utils.setResponse(responseHeaders);
					OutputStream os = exchange.getResponseBody();
					PrintStream out = new PrintStream(os);
						
					H2ConnectionPool h2 = new H2ConnectionPool();
					String add = null;
					if(IOTMain.ADDRESS == "linux")
						add = h2.selectOneConfig("Linux.Fileadd");
					else
						add = h2.selectOneConfig("windows.Fileadd");
					String filename = add+"/"+name;
					System.out.println("文件访问路径："+filename);
					fileOption.safeFile(out,fileOption.readFileToByteBuffer(filename),exchange);
					out.close();
					out.close();
					os.close();

				} catch (IOException ie) {
					ie.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}



